package com.zmh.wt.healthmonitor.listener;


import com.github.benmanes.caffeine.cache.Cache;
import com.zmh.wt.healthmonitor.bo.FeaCurveBO;
import com.zmh.wt.healthmonitor.constant.CacheConstant;
import com.zmh.wt.healthmonitor.constant.Constants;
import com.zmh.wt.healthmonitor.handler.GetBeanHandler;
import com.zmh.wt.healthmonitor.utils.MyPropertyUtil;
import com.zmh.wt.healthmonitor.utils.TxtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class FileListener extends FileAlterationListenerAdaptor {

    private final static String latestFile = "latest_file";

    Cache<String, Object> caffeineCache = GetBeanHandler.getBean("commonCache",Cache.class);

    @Override
    public void onStart(FileAlterationObserver fileAlterationObserver) {
//        log.info("File Listener is started");
    }

    @Override
    public void onDirectoryCreate(File file) {

    }

    @Override
    public void onDirectoryChange(File file) {

    }

    @Override
    public void onDirectoryDelete(File file) {

    }

    /**
     * 监控文件夹内的新文件生成
     */
    @Override
    public void onFileCreate(File file) {
        String fileName = file.getName();//直接就能检测到新文件是哪个？？
        log.info("new file is created, the fileName is :" + fileName);
        //适配旧版本，保留
        String latestFileKey = CacheConstant.getKey(CacheConstant.KEY_REAL_TIME, latestFile);
        String latestFileAbsolutePath = file.getPath();
        Pair<String, String> fileNameAndPathPair = new ImmutablePair<>(fileName, latestFileAbsolutePath);
        caffeineCache.put(latestFileKey, fileNameAndPathPair);

        //最新更新逻辑，更新单个风机key的路径缓存
        //HH_WF10001_WT1_CH1_20210410000000.txt
        Map<String, String> wtFileInfoMap = str2Map(fileName.substring(0, fileName.length() - 4));
        if (Objects.isNull(wtFileInfoMap)){
            return;
        }
        String windturbine = wtFileInfoMap.get("WT");
        String latestFileKeyById = CacheConstant.getLatestFileKeyById(windturbine);
        Pair<String, String> preFilePair = (Pair<String, String>) caffeineCache.asMap().get(latestFileKeyById);
        caffeineCache.put(latestFileKeyById, fileNameAndPathPair);

        //删除旧正常文件
        if (Objects.isNull(preFilePair) ){
            return;
        }
        String preFileAbsolutePath = preFilePair.getRight();
        Map<String, String> preWtFileInfoMap = str2Map(preFileAbsolutePath.substring(0, preFileAbsolutePath.length() - 4));
        String wtState = preWtFileInfoMap.get("ST");

        if (Objects.isNull(wtState) || "".equals(wtState) || wtState.equals(Constants.FAULT.toString())){
            return;
        }

        boolean oldFileDeleteFlag = Boolean.parseBoolean(MyPropertyUtil.getString("realtime.ftp.normal.delete"));

        if (oldFileDeleteFlag){
            TxtUtil.deleteFileByAbsolutePath(preFileAbsolutePath);
        }
    }

    /**
     * 文件名解析
     * @param str
     * @return
     */
    private Map<String, String> str2Map(String str){
        String[] splits = str.split("_");
        Map<String, String> res = new HashMap<>();

        try {
            for (String cur : splits){
                String key = cur.substring(0,2);
                String val = cur.substring(2);
                res.put(key,val);
            }
        } catch (Exception e) {
            return null;
        }
        return res;
    }

    @Override
    public void onFileChange(File file) {

    }

    @Override
    public void onFileDelete(File file) {

    }

    @Override
    public void onStop(FileAlterationObserver fileAlterationObserver) {

    }
}